import { Swiper, Image, NavBar, Card, Tag, Button, Toast, Modal, TextArea } from 'antd-mobile'
import { useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.css'
import iconYes from '../../assets/check_yes.svg'
import iconNo from '../../assets/check_no.svg'
import iconNone from '../../assets/no_check.svg'
import iconDelete from '../../assets/no_check_no.svg'
import {
  fetchReceptionDetail,
  confirmReceptionById,
  cancelReception,
  uploadFile,
} from '../../services/api'

export default function AcceptanceDetail() {
  const navigate = useNavigate()
  const { id } = useParams()
  const [detail, setDetail] = useState<any>(null)
  const [submitting, setSubmitting] = useState(false)
  const [cancelVisible, setCancelVisible] = useState(false)
  const [remark, setRemark] = useState('')
  const [uploadedFiles, setUploadedFiles] = useState<
    Array<{ name: string; url: string; link?: string }>
  >([])

  useEffect(() => {
    if (!id) return
    fetchReceptionDetail(id)
      .then(setDetail)
      .catch(() => null)
  }, [id])

  const images = useMemo(
    () => [
      'https://picsum.photos/800/480?1',
      'https://picsum.photos/800/480?2',
      'https://picsum.photos/800/480?3',
    ],
    [],
  )

  // 文件上传相关函数
  const pickImage = async () => {
    return await new Promise<File[]>(resolve => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.multiple = true
      ;(input as any).capture = 'environment'
      input.onchange = () => {
        resolve(Array.from(input.files || []))
      }
      input.click()
    })
  }

  const handlePick = async () => {
    const files = await pickImage()
    if (!files || files.length === 0) return
    try {
      const proxy = (import.meta as any).env?.VITE_PROXY_TARGET as string | undefined
      const results = await Promise.all(
        files.map(async f => {
          try {
            const res = await uploadFile(f)
            const url = proxy ? `${proxy}${res.link || ''}` : res.link
            const name = res.originalName || res.name || f.name
            return { name, url, link: res.link }
          } catch {
            return null
          }
        }),
      )
      const ok = results.filter(Boolean) as Array<{ name: string; url: string; link?: string }>
      if (ok.length) {
        setUploadedFiles(prev => [...prev, ...ok])
      }
      Toast.show({
        icon: ok.length ? 'success' : 'fail',
        content: ok.length ? `上传成功${ok.length}张` : '上传失败',
      })
    } catch (e) {
      Toast.show({ icon: 'fail', content: '上传失败' })
    }
  }

  const removeFile = (url: string) => {
    setUploadedFiles(prev => prev.filter(f => f.url !== url))
  }

  const buildFilesString = () => {
    return uploadedFiles
      .map(f => f.link || f.url || '')
      .filter(s => !!s)
      .join(',')
  }

  return (
    <div className={styles['accd-page']}>
      <NavBar back onBack={() => navigate(-1)}>
        {detail?.buildingEstateName || detail?.projectName || '接房详情'}
      </NavBar>

      <div className={styles['accd-swiper']}>
        <Swiper autoplay loop>
          {images.map((src, idx) => (
            <Swiper.Item key={idx}>
              <Image src={src} fit="cover" style={{ width: '100%', height: 220 }} />
            </Swiper.Item>
          ))}
        </Swiper>
      </div>

      <div className={styles['accd-section'] + ' ' + styles['accd-overlap']}>
        <Card style={{ borderRadius: 12 }}>
          <div className={styles['accd-title-row']}>
            <div className={styles['accd-title']}>
              {detail?.buildingEstateName || detail?.projectName || '—'}
              <span className={styles['accd-sub']}>
                {detail?.houseNo ? `-${detail.houseNo}` : ''}
              </span>
            </div>
            <div>
              <Tag
                color="primary"
                fill="outline"
                style={{ padding: '0 8px', height: 22, lineHeight: '22px', marginRight: '8px' }}
              >
                {detail?.buildingUnitName || '—'}
              </Tag>
              <Tag
                color="primary"
                fill="outline"
                style={{ padding: '0 8px', height: 22, lineHeight: '22px' }}
              >
                {detail?.houseNo || '—'}
              </Tag>
            </div>
          </div>

          <div className={styles['accd-badges']}>
            {!!detail?.houseTypeName && (
              <Tag color="#E5EFFE" style={{ '--text-color': '#2674FD' }}>
                {detail.houseTypeName}
              </Tag>
            )}
            <Tag color="#E5EFFE" style={{ '--text-color': '#2674FD' }}>
              朝向：{detail?.orientation ?? '—'}
            </Tag>
          </div>

          <div className={styles['accd-desc']}>户型：{detail?.roomType || '—'}</div>
          <div className={styles['accd-location']}>{detail?.remark || ''}</div>

          <div className={styles['accd-feats']}>
            <Tag color="#D6D6D6" fill="outline">
              品质精装
            </Tag>
            <Tag color="#D6D6D6" fill="outline">
              独立阳台
            </Tag>
            <Tag color="#D6D6D6" fill="outline">
              交通便利
            </Tag>
          </div>
        </Card>
      </div>

      <div className={styles['accd-section']}>
        <Card style={{ borderRadius: 12 }}>
          <div className={styles['accd-card-title']}>租房信息</div>
          <div className={styles['accd-kv']}>
            <span>姓名：</span>
            <em>{detail?.applicationName || '—'}</em>
          </div>
          <div className={styles['accd-kv']}>
            <span>联系电话：</span>
            <em>{detail?.phone || '—'}</em>
          </div>
          <div className={styles['accd-kv']}>
            <span>租期：</span>
            <em>
              {detail?.leaseTermStart || '—'}—{detail?.leaseTermEnd || '—'}
            </em>
          </div>
          <div className={styles['accd-kv']}>
            <span>合同：</span>
            <a
              className={styles['accd-link']}
              onClick={() => navigate(`/contract/${detail?.id || id || 1}`)}
            >
              核对合同
            </a>
            <img
              src={
                detail?.contractVerification === 1
                  ? iconYes
                  : detail?.contractVerification === 2
                  ? iconNo
                  : iconNone
              }
              alt="cv1"
              style={{ width: 18, height: 18, verticalAlign: 'middle', marginRight: 6 }}
            />
          </div>
          <div className={styles['accd-kv']}>
            <span>设施：</span>
            <a
              className={styles['accd-link']}
              onClick={() => navigate(`/facility/${detail?.id || id || 1}`)}
            >
              核对设施
            </a>
            <img
              src={detail?.facilityVerification === 1 ? iconYes : iconNone}
              alt="fv"
              style={{ width: 18, height: 18, verticalAlign: 'middle', marginLeft: 6 }}
            />
          </div>
          <div className={styles['accd-kv']}>
            <span>附件：</span>
            <a className={styles['accd-link']} onClick={handlePick}>
              上传附件
            </a>
            {uploadedFiles.length > 0 && (
              <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {uploadedFiles.map((file, index) => (
                  <div
                    key={file.url || index}
                    style={{ position: 'relative', display: 'inline-block' }}
                  >
                    <img
                      src={file.url}
                      alt={file.name}
                      style={{
                        width: 60,
                        height: 60,
                        objectFit: 'cover',
                        borderRadius: 4,
                        cursor: 'pointer',
                      }}
                      onClick={() => window.open(file.url, '_blank')}
                    />
                    <img
                      src={iconDelete}
                      alt="删除"
                      style={{
                        position: 'absolute',
                        top: -8,
                        right: -8,
                        width: 20,
                        height: 20,
                        cursor: 'pointer',
                      }}
                      onClick={() => removeFile(file.url)}
                    />
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>
      </div>

      <div className={styles['accd-bottom']}>
        <Button
          size="large"
          style={{ fontSize: '14px' }}
          className={`${styles['accd-btn']} ${styles['ghost']}`}
          disabled={submitting}
          onClick={() => {
            if (!id && !detail?.id) return
            setCancelVisible(true)
          }}
        >
          取消接房
        </Button>
        <Button
          size="large"
          style={{ fontSize: '14px' }}
          className={`${styles['accd-btn']} ${styles['primary']}`}
          disabled={submitting}
          onClick={async () => {
            try {
              setSubmitting(true)
              const files = buildFilesString()
              await confirmReceptionById(detail?.id as any, detail?.houseId as any, files)
              Toast.show({ icon: 'success', content: '已确认接房' })
              navigate(-1)
            } catch (e) {
            } finally {
              setSubmitting(false)
            }
          }}
        >
          确认接房
        </Button>
      </div>
      <Modal
        visible={cancelVisible}
        onClose={() => setCancelVisible(false)}
        content={
          <div>
            <div style={{ marginBottom: 8, color: '#666' }}>请输入取消接房原因</div>
            <TextArea
              value={remark}
              onChange={val => setRemark(val)}
              placeholder="请输入退取消接房原因"
              rows={3}
              maxLength={200}
              showCount
            />
          </div>
        }
        actions={[
          {
            key: 'cancel',
            text: '再想想',
            onClick: () => setCancelVisible(false),
          },
          {
            key: 'ok',
            text: submitting ? '提交中...' : '提交',
            onClick: async () => {
              if (!id && !detail?.id) return
              if (!remark.trim()) {
                Toast.show({ icon: 'fail', content: '请填写取消接房原因' })
                return
              }
              try {
                setSubmitting(true)
                const files = buildFilesString()
                await cancelReception({
                  id: detail?.id ?? '',
                  houseId: detail?.houseId ?? '',
                  remark: remark?.trim() || undefined,
                  files: files || undefined,
                })
                setRemark('')
                Toast.show({ icon: 'success', content: '已取消接房' })
                navigate(-1)
              } finally {
                setSubmitting(false)
                setCancelVisible(false)
              }
            },
          },
        ]}
      />
    </div>
  )
}
